package cn.tworice.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

/**
 * 文件上传
 * @author 二饭[tworice@sina.cn][2022/1/30 22:45]
 */
@Slf4j
@Component
public class UploadUtil {

    /**
     * 上传文件到upload目录下
     * @return 返回上传后的路径+文件名称
     * @author 二饭[tworice@sina.cn][2022/1/30 22:39]
     */
    public String uploadFile(MultipartFile file) {
        String path = null;
        try {
            if (file == null || file.getOriginalFilename()==null) {
                return null;
            }
            //获取文件后缀
            String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1)
                    .toLowerCase();
            String pikId = UUID.randomUUID().toString().replaceAll("-", "");
            path = "/upload/" + pikId + "." + fileExt;
            String upload=System.getProperty("user.dir")+"\\target\\classes\\static\\";
            // 判断路径是否存在，不存在则创建文件夹
            File file1 = new File(upload+"upload");
            if (!file1.exists()) {
                log.info("目标文件夹不存在，进行创建");
                file1.mkdirs();
            }
            file.transferTo(new File(upload+path));
        }catch (Exception e){
            log.error("上传文件失败");
            e.printStackTrace();
            return null;
        }
        log.info("上传文件成功");
        return path;
    }

    /**
     * 上传文件到指定路径
     * 只能上传到项目目录中
     * @author 二饭[tworice@sina.cn][2022/1/30 22:41]
     */
    public String uploadFile(MultipartFile file, String targetPath) {
        String path = null;
        try {
            if (file == null || file.getOriginalFilename()==null) {
                return null;
            }
            //获取文件后缀
            String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1)
                    .toLowerCase();
            String pikId = UUID.randomUUID().toString().replaceAll("-", "");
            path = "/"+targetPath+"/" + pikId + "." + fileExt;
            String upload=System.getProperty("user.dir")+"\\target\\classes\\static\\";
            file.transferTo(new File(upload+path));
        }catch (Exception e){
            e.printStackTrace();
            log.error("上传文件失败");
            return null;
        }
        return path;
    }

    /**
     * 获取目标地址文件的Base64码
     * @param path 文件路径
     * @return java.lang.String Base64码
     * @author 二饭 [2022/9/24]
     **/
    public String getBase64(String path) {
        Base64.Encoder encoder = Base64.getEncoder();
        File file = new File(path);
        FileInputStream fis = null;
        String newStr = "";
        try {
            fis = new FileInputStream(file);
            long size = file.length();
            byte[] temp = new byte[(int) size];
            fis.read(temp, 0, (int) size);
            byte[] data = temp;
            data = encoder.encode(data);
            newStr = "data:image/jpg;base64," + new String(data);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return newStr;
    }
}
